<?php
/*
 * Smarty plugin
 * -------------------------------------------------------------
 * File:     function.select.php
 * Type:     function
 * Name:     select
 * Purpose:  outputs html for a form select
 * -------------------------------------------------------------
 */
function smarty_function_select($params, &$smarty) {
    $object = $smarty->_tpl_vars[$params['object']];
	$mapping = $params['object'] . '.' . $params['name'];
	$readonly = @$params['readonly'] == true;
    
    $html = '<label>';
    $html .= $params['required'] == true ? '<em>*</em>' : '';
    $html .= $params['label'] . ':</label><br />';
	
	if($readonly === false) {
		$error = Adroit::$alerts->getAlertById($mapping, AdroitAlertHandler::$TYPE_ERROR);
		$html .= '<select name="' . $mapping . '" id="' . mapping . '" style="' . @$params['style'] . '" class="' . ($error !== null ? 'input-error' : '') . '">';
		if(@$params['blank'] == true) {
			$html .= '<option value="">' . @$params['blankLabel'] . '</option>';
		}
	    if(@isset($params['property'])) {
			foreach($smarty->_tpl_vars[$params['from']] AS $item) {
	            $html .= '<option value="' . $item->$params['property'] . '"';
	            if($item->$params['property'] == $object->$params['name']) {
	                $html .= ' selected ';
	            }
	            $html .= '>' . $item->$params['labelProperty'] . '</option>';
	        }
	    }else {
	        foreach($smarty->_tpl_vars[$params['from']] AS $key => $value) {
	            $html .= '<option value="' . $key . '"';
	            if($key == $object->$params['name']) {
	                $html .= ' selected ';
	            }
	            $html .= '>' . $value . '</option>';
	        }
	    }
	    $html .= '</select>';
		if($error != null) {
			$html .= '<span class="input-error-message">' . $error->message . '</span>';
		}
	}else {
		$propertyValue = '';
		if(@$params['keyValue'] == true) {
	        foreach($smarty->_tpl_vars[$params['from']] AS $key => $value) {
	            if($key == $object->$params['name']) {
	                $propertyValue = $value;
	            }
	        }
	    }else {
	        foreach($smarty->_tpl_vars[$params['from']] AS $item) {
	            if($item->$params['property'] == $object->$params['name']) {
	                $propertyValue = $item->$params['labelProperty'];
	            }
	        }
	    }
		$html .= '<span class="data">' . $propertyValue . '</span>';
	}
    
    return $html;
}
?>